import dayjs from "dayjs";
import eventBus from "../utils/event-bus";
import { isBoolean, isNumber } from "cl-admin/utils";
import defaultAvatar from "@/assets/img/men.png";
import logo from "@/assets/logo/logo.png";
import { uniqBy } from "@/utils";

// import chatDB from "../utils/db";
import store from 'store'
export default {
	state: {
		list: store.get("friends") || [],
		current: null,
		visible: true,
		roomId: null
	},

	getters: {
		// 当前会话
		session: state => state.current,
		// 会话列表
		sessionList: state => state.list,
		// 是否显示会话列表
		sessionVisible: state => state.visible,
		// 房间ID
		roomId: state => state.roomId
	},
	actions: {
		async getLocalSesstionList({ commit }) {
			// const friends = await chatDB.getFriends();
			const friends = store.get("friends") || []
			commit("SET_SESSION_LIST", friends);
			return friends;
		},
		async getSessionList({ commit, state, dispatch }, params) {
			dispatch("getLocalSesstionList");
			return this.$service.chats
				.friendList(params)
				.then(res => {
					let system = {
						cca_avatar: logo,
						cca_id: 0,
						cca_name: "工作通知",
						type: 'system',
						cr_id: 0,
						created_at: parseInt(Date.now() / 1000),
						created_at_text: ""
					}
					let friends = [system, ...res].map(v => {
						const item = state.list.find(e => e.cr_id == v.cr_id);
						return {
							...v,
							...item,
							cca_avatar: v?.cca_avatar || defaultAvatar,
							unread_total: item?.unread_total ?? 0,
							updated_at: item?.updateTime ?? v?.created_at * 1000,
							updateTime: item?.updateTime ?? v?.created_at * 1000
						};
					});
					store.set("friends", friends)
					commit("SET_SESSION_LIST", friends);
					// chatDB.setFriends(friends);
					return friends;
				})
		},
		async setSession({ commit, dispatch }, data) {
			const friends = store.get("friends") || []
			let index = friends.findIndex(v => v.cca_id == data.cca_id);
			if (index == -1) return
			friends[index] = {
				...friends[index],
				...data
			};
			friends[index].unread_total = 0
			store.set("friends", friends)
			commit("SET_SESSION_LIST", friends);
			return dispatch("putSession", data).done(() => {
				commit("SET_SESSION", friends[index]);
			});
		},
		async putSession({ dispatch }, data) {
			const friends = store.get("friends") || []
			if (!data) return
			let index = friends.findIndex(v => v.cr_id == data.cr_id);
			if (index == -1) return
			friends[index] = {
				...friends[index],
				...data
			};
			store.set("friends", friends)
			return Promise.all([
				// chatDB.setFriend(data),
				// chatDB.putUnread(data.cr_id, { reset: true, updated: false }),
				dispatch('putUnread', { cr_id: data.cr_id, reset: true, updated: false })
			]);
		},
		setUnread({ commit }, { cr_id, unread_total = 0 }) {
			if (cr_id == undefined) return
			const friends = store.get("friends") || []
			let index = friends.findIndex(v => v.cr_id == cr_id);
			friends[index].unread_total += unread_total
			store.set("friends", friends)
			commit("SET_SESSION_LIST", friends);
			return friends
		},
		async putUnread({ commit }, { cr_id, reset = false, updated = true }) {
			if (cr_id == undefined) return
			const friends = store.get("friends") || []
			let index = friends.findIndex(v => v.cr_id == cr_id);
			if (index == -1) return
			console.log('putUnread');
			if (reset) {
				friends[index].unread_total = 0;
			} else {
				friends[index].unread_total += 1;
			}
			if (updated) {
				friends[index].updated_at = Date.now();
			}
			// console.log('putUnread');
			store.set("friends", friends)
			commit("SET_SESSION_LIST", friends);
			return friends
		},
		async putLastMsg({ commit }, { cr_id, msg = {}, updated = true }) {
			if (cr_id == undefined) return
			const friends = store.get("friends") || []
			let index = friends.findIndex(v => v.cr_id == cr_id);
			if (index == -1) return
			friends[index].last_msg = msg.content;
			friends[index].last_msg_type = msg.content_type;
			if (msg.created_at) {
				let updated_at = isNumber(msg.created_at) ? msg.created_at * 1000 : dayjs(msg.created_at).valueOf()
				friends[index].updated_at = updated_at;
			}
			// console.log(msg, info);
			// console.log('putLastMsg', updated);
			if (updated) {
				friends[index].updated_at = Date.now();
			}
			// console.log('friend', friends[index]);
			store.set("friends", friends)
			commit("SET_SESSION_LIST", friends);
			return friends
		},
		async clearSessionList() {
			// chatDB.clearFriends();
			store.remove("friends")
			commit("SET_SESSION_LIST", []);
		}
	},
	mutations: {
		// 设置会话信息
		SET_SESSION(state, data) {
			state.current = data;
			eventBus.$emit("message.refresh", { page: 1 });
		},

		SET_SESSION_ID(state, data) {
			state.roomId = data;
		},

		// 清空会话信息
		CLEAR_SESSION(state) {
			state.current = null;
			state.roomId = null;
		},

		// 设置会话列表
		SET_SESSION_LIST(state, data) {
			// state.list = uniqBy(data, 'cca_id');
			state.list = data;

		},

		// 清空会话列表
		CLEAR_SESSION_LIST(state) {
			state.list = [];
			// chatDB.clearTable();
			store.remove("friends")
		},

		// 打开会话列表
		OPEN_SESSION(state, val) {
			state.visible = isBoolean(val) ? val : !state.visible;
		},

		// 关闭会话列表
		CLOSE_SESSION(state) {
			state.visible = false;
			state.session = null;
			state.roomId = null;
		}
	}
};
